package com.snow.useviewdemo.qiniuplay.video;

import android.app.Application;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;

import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.PLOnErrorListener;
import com.pili.pldroid.player.PLOnInfoListener;
import com.snow.useviewdemo.APPApplication;


/**
 * author : zyt
 * e-mail : 632105276@qq.com
 * date   : 2019/06/10
 * desc   : 视频管理===只播放一次调用
 */

public class PlayOnceVideoManager {
    private static PlayOnceVideoManager videoManager;
    //ali视频播放器
    private PLMediaPlayer aliyunVodPlayer;
    //不写静态会一直是空
    private static PlayOnceStateListener playerListener;
    private String lastPlayUrl;

    private PlayOnceVideoManager() {
        initVodPlayer();
    }

    public static PlayOnceVideoManager init() {
        if (videoManager == null) {
            synchronized (PlayOnceVideoManager.class) {
                if (videoManager == null) {
                    videoManager = new PlayOnceVideoManager();
                }
            }
        }
        return videoManager;
    }

    // 初始化播放器
    private void initVodPlayer() {
        aliyunVodPlayer = new PLMediaPlayer(APPApplication.getInstance());
        //循环播放
//        aliyunVodPlayer.setOnCircleStartListener(new MyCircleStartListener(this));
        //准备播放监听
        aliyunVodPlayer.setOnPreparedListener((var1) -> {
            if (playerListener != null) {
                Log.e("snowzhao", "准备播放===========");
                aliyunVodPlayer.start();
            }
        });
        aliyunVodPlayer.setOnInfoListener(new PLOnInfoListener() {
            @Override
            public void onInfo(int i, int i1) {
                if (i == MEDIA_INFO_VIDEO_RENDERING_START) {
                    if (playerListener != null) {
                        Log.e("snowzhao", "播放第一帧完成===========");
                        handler.sendEmptyMessage(10001);
                        playerListener.startPlayMusic();
                    }
                }
            }
        });
//        //第一帧画面展示
//        aliyunVodPlayer.setOnFirstFrameStartListener(() -> {
//            if (playerListener != null) {
//                handler.sendEmptyMessage(10001);
//                playerListener.startPlayMusic();
//            }
//        });
//        //播放错误
        aliyunVodPlayer.setOnErrorListener(i -> {
                    Log.e("snowzhao", "播放错误===========" + i);
                    return false;
                }
        );
//        aliyunVodPlayer.setOnErrorListener((int arg0, int arg1, String msg) -> {
//            //出错时处理，查看接口文档中的错误码和错误消息
//        });
        //播放完成监听
        aliyunVodPlayer.setOnCompletionListener(() -> {
            if (playerListener != null) {
                playerListener.playComplement();
            }
        });
        aliyunVodPlayer.setOnSeekCompleteListener(() -> {
            //seek完成时触发
        });
        AVOptions options = new AVOptions();
        // 设置拖动模式，1 位精准模式，即会拖动到时间戳的那一秒；0 为普通模式，会拖动到时间戳最近的关键帧。默认为 0
        options.setInteger(AVOptions.KEY_SEEK_MODE, 1);
        // 请在开始播放之前配置
        aliyunVodPlayer.setAVOptions(options);
        aliyunVodPlayer.setWakeMode(APPApplication.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);

//        aliyunVodPlayer.setOnStoppedListner(() -> {
//            //使用stop功能时触发
//        });
//        aliyunVodPlayer.setOnChangeQualityListener(new IAliyunVodPlayer.OnChangeQualityListener() {
//            @Override
//            public void onChangeQualitySuccess(String finalQuality) {
//                //视频清晰度切换成功后触发
//            }
//
//            @Override
//            public void onChangeQualityFail(int code, String msg) {
//                //视频清晰度切换失败时触发
//            }
//        });
//        //设置十秒网络超时
//        aliyunVodPlayer.setNetworkTimeout(10000);
//        aliyunVodPlayer.setVideoScalingMode(IAliyunVodPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
    }

    /**
     * 播放
     */
    public void playVideo(String playUrl) {
        try {
            if (null == aliyunVodPlayer || TextUtils.isEmpty(playUrl)) {
                return;
            }
            lastPlayUrl = playUrl;
            //播放前一定要重置====这里初始化可能会耗时操作，在弹框点击时会卡顿
//        ThreadPoolManager.getInstance().execute(() -> {
            //必须先调用stop然后在调用reset，最后调用prepareAsync，否则有时会崩溃
            aliyunVodPlayer.stop();
            aliyunVodPlayer.setDataSource(playUrl);
//            aliyunVodPlayer.reset();
//            AliyunLocalSource.AliyunLocalSourceBuilder asb = new AliyunLocalSource.AliyunLocalSourceBuilder();
////        asb.setSource("http://player.alicdn.com/video/aliyunmedia.mp4");
//            asb.setSource(playUrl);
//        asb.setTitle("");
            aliyunVodPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        });
    }


    /**
     * 获得播放player
     *
     * @return
     */
    public PLMediaPlayer getAliyunVodPlayer() {
        if (aliyunVodPlayer == null) {
            aliyunVodPlayer = new PLMediaPlayer(APPApplication.getInstance());
        }
        return aliyunVodPlayer;
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        return aliyunVodPlayer.isPlaying();
    }

    /**
     * 暂停
     */
    public void pause() {
        if (null != aliyunVodPlayer) {
            aliyunVodPlayer.pause();
            handler.removeMessages(10001);
        }
    }

    /**
     * 恢复
     */
    public void resume() {
        if (null != aliyunVodPlayer) {
            aliyunVodPlayer.start();
            handler.sendEmptyMessage(10001);
        }
    }

    /**
     * 重新播放
     */
    public void rePlay() {
        if (null != aliyunVodPlayer) {
            playVideo(lastPlayUrl);
        }
    }

    /**
     * 结束
     */
    public void stop() {
        if (null != aliyunVodPlayer) {
            aliyunVodPlayer.stop();
            handler.removeMessages(10001);
        }
    }

    //播放进度监听
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 10001:
                    if (playerListener != null) {
                        playerListener.playProgress(aliyunVodPlayer.getCurrentPosition());
                    }
                    handler.sendEmptyMessageDelayed(10001, 1000);
                    break;
            }
            return false;
        }
    });

    /**
     * 音乐播放相关监听
     *
     * @param playListener
     */
    public void setPlayStateListener(PlayOnceStateListener playListener) {
        playerListener = playListener;
    }

}
